package com.itmck.controller;

import com.itmck.client.MySimpleClient;
import com.itmck.response.ApiResultResponse;
import com.itmck.response.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 太阳当空照,花儿对我笑
 * <p>
 * Create by M ChangKe 2021/11/18 9:28
 **/

@Slf4j
@RestController
@Api(value = "MyController", tags = "MyController")
public class MyController {


    @Resource
    MySimpleClient mySimpleClient;


    @GetMapping("/getString")
    public String simpleGet(@RequestParam(required = false) String name) {
        return "hello " + name;
    }

    @GetMapping("/getStringApi")
    public ApiResultResponse<String> getHelloApi(@RequestParam(required = false) String name) {
        return ApiResultResponse.ok(name);
    }

    @PostMapping("/postJson")
    public ApiResultResponse<User> postJson(@RequestBody User user) {
        return ApiResultResponse.ok(user);
    }

    @ApiOperation(value = "上传", notes = "上传", consumes = "multipart/form-data")
    @PostMapping("upload")
    public ApiResultResponse<String> uploadFile(@RequestParam(value = "file") MultipartFile file) {
        mySimpleClient.uploadFile(file);
        return ApiResultResponse.ok("");
    }


    @ApiOperation(value = "下载", notes = "下载")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "文件名", dataType = "String", paramType = "query")
    })
    @GetMapping("download")
    public void download(String fileName, HttpServletResponse response) {
        InputStream fis = mySimpleClient.downLoadFile(fileName);
        downLoadFileByInputStream(fileName, response, fis);
    }

    private void downLoadFileByInputStream(String fileName, HttpServletResponse response, InputStream fis) {
        response.setContentType("application/octet-stream");
        response.setHeader("content-disposition", "attachment;fileName=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
        try (
                ServletOutputStream os = response.getOutputStream()
        ) {
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
            os.flush();
        } catch (IOException e) {
            log.error("下载失败", e);
        }
    }


}